<template>
  <!-- 分配权限的弹层 -->
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="showAssignDialog"
    @close="closeAssignDialog"
  >
    <el-tree
      ref="tree"
      :data="list"
      node-key="id"
      show-checkbox
      :props="{ label: 'name' }"
      default-expand-all
      check-strictly
    ></el-tree>

    <!-- 权限点数据展示 -->
    <template #footer>
      <el-button @click="closeAssignDialog">取消</el-button>
      <el-button type="primary" @click="assignPerm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { tranListToTreeDate } from '@/utils/index.js'
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      list: [],
      currId: ''
    }
  },
  created () {
    this.getPermissionList()
  },
  methods: {
    // 点击确定分配权限
    async assignPerm () {
      await assignPerm({ id: this.currId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.$emit('update:showAssignDialog', false)
    },
    closeAssignDialog () {
      this.$emit('update:showAssignDialog', false)
      // 给树形组件清空勾选状态 ===> 传一个空数组 ===> 不然会报错: keys.forEach is not a function
      this.$refs.tree.setCheckedKeys([])
    },
    // 获取页面和功能权限列表
    async getPermissionList () {
      const data = await getPermissionList()
      this.list = tranListToTreeDate(data)
      // console.table(this.list)
    },
    // 根据id获取角色的权限进行回显
    async getRoleDetail (id) {
      const { permIds } = await getRoleDetail(id)
      // console.log('角色具体权限', permIds)
      // 存储当前点击的角色id
      this.currId = id
      // 调用树形组件方法setCheckedKeys 传入id 让树形组件的checkbox默认勾选回显
      this.$refs.tree.setCheckedKeys(permIds)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
